package com.wry.wry_test.feign.config;


import java.util.Map;
import java.util.Random;

/**
 * @Author: wangrongyi
 * @Date: 2024/7/24 16:16
 * @Description: 加权随机算法
 */
public class WeightRandom implements LoadBalanceService {
    private final LoadBalanceProperties properties;

    private final Random random = new Random();

    public WeightRandom(LoadBalanceProperties loadBalanceProperties) {
        this.properties = loadBalanceProperties;
    }

    @Override
    public synchronized String getServerAddress() {

        int totalWeight = 0;
        for (Integer value : properties.getWeight().values()) {
            totalWeight += value;
        }
        int randomWeight = random.nextInt(totalWeight);
        for (Map.Entry<String, Integer> entry : properties.getWeight().entrySet()) {
            randomWeight -= entry.getValue();
            if (randomWeight < 0) {
                return entry.getKey();
            }
        }
        return null;
    }
}
